package PlayTravel.Activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


// ----------------------------------------------------------------------

public class StillCamera extends Activity implements OnClickListener{
    private Preview mPreview;
    private String imgName = null;
    private Integer modifyIndex = 1;
    private Integer onFlag = 0;
   
    @Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Hide the window title.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.stillcamera);
        FrameLayout frame = (FrameLayout) findViewById(R.id.frame);

        // Create our Preview view and set it as the content of our activity.
        mPreview = new Preview(this);
        frame.addView(mPreview);
        
        Intent intent = getIntent();			
		modifyIndex = (Integer) intent.getIntExtra("modifyIndex", -1);		
        
		Long tmpCal = null;
		Calendar cal = Calendar.getInstance();
		tmpCal = cal.getTimeInMillis();
		imgName = tmpCal.toString() + ".jpg";
        
        //imgName = imgNumber.toString() + ".jpg";
        
        frame.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
            	mPreview.capture(new Camera.PictureCallback() {

                    public void onPictureTaken(byte[] data, Camera camera) {
                    	if (onFlag == 1) return ;
                    	onFlag = 1;
                        Log.v("Still", "Image data received from camera");
                        FileOutputStream fos;
                        try {
                            // Fully qualified path name. In this case, we
                            // use the Files subdir
                        	String FILE_ROOT = "/sdcard/";
                        	String dirName = "playtravel";
                        	String fullSrc = FILE_ROOT + dirName + "/" + imgName;                      	
                        	
                        	File directory = new File(FILE_ROOT + dirName + "/");
                        	
                        	if (directory.exists() == false)
                        	{
                        		directory.mkdir();                        	
                        	}
                            	                            
                            fos = new FileOutputStream(fullSrc);
                            fos.write(data);
                            fos.close();                            
                            
                        	Intent intent = getIntent();
             				intent.putExtra("imgSrc",fullSrc);	
             				setResult(RESULT_OK,intent);
             				
             				finish(); 

                        } catch (Exception e) {
                            Log.e("Still", "Error writing file", e);
                        }
                    }
                });
            }
        });
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{			
		}
	}


// ----------------------------------------------------------------------
}
class Preview extends SurfaceView implements SurfaceHolder.Callback {
    SurfaceHolder mHolder;
    Camera mCamera;
    Camera.Parameters paramete;

    Preview(Context context) {
        super(context);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        mCamera = Camera.open(); 
        
        try {
           mCamera.setPreviewDisplay(holder);
        } catch (IOException exception) {
            mCamera.release();
            mCamera = null;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        // Because the CameraDevice object is not a shared resource, it's very
        // important to release it when the activity is paused.
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }


    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.05;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = mCamera.getParameters();

        List<Size> sizes = parameters.getSupportedPreviewSizes();        
        Size optimalSize = getOptimalPreviewSize(sizes, w, h);
        parameters.setPreviewSize(optimalSize.width, optimalSize.height);
        
        List<Size> sizes2 = parameters.getSupportedPictureSizes();
        
        Integer minIndex = 0;
        Integer minWidth = 999999;
        
        for (Integer i = 0 ; i < sizes2.size() ; i++)
        {
        	if (sizes2.get(i).width < minWidth)
        	{
        		minIndex = i;
        		minWidth = sizes2.get(i).width;
        	}
        }
        
        
        parameters.setPictureSize(sizes2.get(minIndex).width,sizes2.get(minIndex).height);

        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }
    
    public boolean capture(Camera.PictureCallback jpegHandler) {
        if (mCamera != null) {
        	mCamera.takePicture(null, null, jpegHandler);
            return true;
        } else {
            return false;
        }
    }

}
